<script setup>
import '@/assets/common/common.scss'
import { ref } from 'vue'
import { ArrowCircleRight, ErrorPicture, Refresh } from '@icon-park/vue-next'
import { checkCodeService, createCodeService } from '@/api/common.js'
import { toPhoto } from '@/utils/base64Utils.js'
import { findUsernameService } from '@/api/user.js'
import { useRouter } from 'vue-router'
import { useForgotState } from '@/stores/index.js'


const router = useRouter()
const forgotState = useForgotState()

const user = ref({
  username: '',
  code: ''
})

// 生成验证码图片
const photo = ref('')
const isSpinning = ref(false) // 控制旋转状态

const createCode = async () => {
  if (isSpinning.value) return // 防止重复点击
  isSpinning.value = true // 开始旋转

  const resp = await createCodeService()
  if (resp.code === 1) {
    photo.value = toPhoto(resp.data)
  }

  setTimeout(() => {
    isSpinning.value = false // 停止旋转
  }, 1000) // 控制旋转时间
}
createCode()

const rules = ref({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 15, message: '用户名长度3-15字符', trigger: 'blur' }
  ],
  code: [{ required: true, message: '验证码不能为空', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        try {
          const resp = await checkCodeService(value)
          if (resp.code !== 1) {
            await createCode()
            callback(new Error('验证码不正确'))
          } else {
            callback()
          }
        } catch {
          await createCode()
          callback(new Error('验证码验证失败'))
        }
      },
      trigger: 'blur'
    }
  ]
})
const formRef = ref()
const onSubmit = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const resp = await findUsernameService(user.value)

      if (resp.code === 1) {
        forgotState.setFUser(user.value)
        await router.push('/user/forgot/email')
      }
    } else {
      console.log('验证失败')
    }
  })
}
</script>

<template>
  <el-form
    :model="user"
    :rules="rules"
    ref="formRef"
    style="max-width: 320px"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名：" prop="username">
      <el-input placeholder="请输入你的用户名" style="width: 300px" v-model="user.username" />
    </el-form-item>

    <el-form-item class="code-photo" label="验证码：" prop="code">
      <el-image style="border-radius: 5px" :src="photo" @click.prevent="createCode">
        <template #error>
          <div class="image-slot">
            <error-picture theme="outline" size="50" fill="#333" :strokeWidth="2" />
          </div>
        </template>
      </el-image>

      <span class="icon-center" @click.prevent="createCode">
        <refresh :strokeWidth="6" :class="{ spinning: isSpinning }" />&nbsp;看不清，点击换一张。
      </span>

      <br>
      <el-input placeholder="请输入正确的验证码" style="margin: 5px 0" v-model="user.code" />
    </el-form-item>

    <div style=" text-align: center;margin-bottom: 15px">
      <el-button style="width: 250px" size="large" round type="primary" @click="onSubmit">
        下一步&nbsp;<arrow-circle-right class="icon-center" theme="outline" size="18" :strokeWidth="4" />
      </el-button>
    </div>
  </el-form>
</template>

<style scoped>
.demo-ruleForm {
  width: 400px;
  margin: 0 auto;

  .code-photo {
    .icon-center {
      margin-left: 5px;
      font-size: 12px;
      font-weight: bold;
      cursor: pointer;
      color: #11659a;
    }
  }
}


</style>
